using System;
using System.IO;
using System.Threading;

namespace XSResearch
{
    public enum LogLevel
    {
        Debug,
        Info,
        Warning,
        Error
    }

    public class AppLogger
    {
        private readonly string logFilePath;
        private readonly object lockObj = new object();

        public AppLogger(string path = "app.log")
        {
            logFilePath = path;
            try 
            {
                var dir = Path.GetDirectoryName(path);
                if (!string.IsNullOrEmpty(dir) && !Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException($"Failed to initialize logger directory: {ex.Message}");
            }
        }

        private const long MaxLogSize = 10 * 1024 * 1024; // 10MB
        
        public void Log(string message, LogLevel level = LogLevel.Info)
        {
            var entry = $"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] [{level}] {message}";
            
            lock (lockObj)
            {
                Console.WriteLine(entry);
                
                try 
                {
                    if (File.Exists(logFilePath) && new FileInfo(logFilePath).Length > MaxLogSize)
                    {
                        var archivePath = $"{logFilePath}.{DateTime.Now:yyyyMMddHHmmss}";
                        File.Move(logFilePath, archivePath);
                    }
                    
                    File.AppendAllText(logFilePath, entry + Environment.NewLine);
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"[Error] Failed to write log: {ex.Message}");
                }
            }
        }
    }
}